package com.jzoom.zoom.admin.controllers;

import com.jzoom.zoom.admin.models.DaoService;
import com.jzoom.zoom.caster.codec.Base64;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.dao.DaoException;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.web.annotations.Controller;
import com.jzoom.zoom.web.annotations.JsonResponse;
import com.jzoom.zoom.web.exception.StatusException;

import java.util.List;

@Controller(key="sql")
public class SqlController {

    @Inject
    private DaoService daoService;

    @JsonResponse
    public List<Record> query(
            String ds,
            String content
    ){
        String sql = new String(Base64.decodeFast(content));
        sql = sql.trim();
        Dao dao = daoService.getDao(ds);
        String parsedSql = sql.toUpperCase();
        if (parsedSql.startsWith("UPDATE") || parsedSql.startsWith("ALTER") || parsedSql.startsWith("DELETE")
                || parsedSql.startsWith("INSERT") || parsedSql.startsWith("CREATE")) {


            dao.ar().executeUpdate(sql);

            return null;
        }
        StringBuilder sb = dao.getDriver().buildPage(
                new StringBuilder(sql),
                0,
                100
        );

        try {
            List<Record> list = dao.ar().executeQuery(sb.toString());
            return list;
        } catch (DaoException e) {
            Exception ex = (Exception) e.getCause();
            throw new StatusException.ApiError("sql错误" + ex.getMessage());
        }



    }

}
